<template>
    <div class="club-approval">
      <el-card class="approval-card">
        <div slot="header" class="card-header">
          <span><i class="el-icon-s-check"></i> 社团审核</span>
          <!-- <el-button type="primary" size="small" @click="refreshClubList">刷新</el-button> -->
        </div>
        
        <div class="filter-container">
          <!-- <el-input
            v-model="clubListQuery.keyword"
            placeholder="社团名称/申请人"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleClubFilter"
          />
          <el-select
            v-model="clubListQuery.category"
            placeholder="社团类型"
            clearable
            style="width: 130px"
            class="filter-item"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="clubListQuery.status"
            placeholder="审核状态"
            clearable
            style="width: 130px"
            class="filter-item"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleClubFilter"
          >
            搜索
          </el-button> -->
        </div>
        
        <el-table
          :data="clubList"
          style="width: 100%"
          v-loading="clubListLoading"
          border
          fit
          highlight-current-row
        >
          <el-table-column prop="name" label="社团名称"  align="center" />
          
          <el-table-column prop="category" label="类别"  align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.category">
                <el-tag 
                  v-for="(tag, index) in scope.row.category.split(',')" 
                  :key="index"
                  :type="getTagType(tag.trim())"
                  style="margin-right: 5px; margin-bottom: 5px;">
                  {{ tag.trim() }}
                </el-tag>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <!-- <el-table-column prop="president" label="申请人"  align="center" /> -->
          
          <el-table-column prop="createTime" label="申请时间"  align="center" />
          
          <el-table-column prop="status" label="状态"  align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="openClubDetail(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="clubListQuery.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="clubListQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="clubTotal"
          >
          </el-pagination>
        </div>
      </el-card>
      
      <!-- 社团详情对话框 -->
      <el-dialog
        title="社团申请详情"
        :visible.sync="clubDetailVisible"
        width="70%"
        :before-close="handleCloseDialog">
        
        <div v-if="currentClub" class="club-detail">
          <!-- 社团基本信息 -->
          <el-descriptions title="基本信息" :column="2" border>
            <!-- <el-descriptions-item label="社团ID">{{ currentClub.id }}</el-descriptions-item> -->
            <el-descriptions-item label="社团名称">{{ currentClub.name }}</el-descriptions-item>
            <el-descriptions-item label="社团类型">
              <template v-if="currentClub.category">
                <el-tag 
                  v-for="(tag, index) in currentClub.category.split(',')" 
                  :key="index"
                  :type="getTagType(tag.trim())"
                  style="margin-right: 5px; margin-bottom: 5px;">
                  {{ tag.trim() }}
                </el-tag>
              </template>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="成立日期">{{ formatDateTime(currentClub.createTime) || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTypeByValue(currentClub.stat)">
                {{ getStatusTextByValue(currentClub.stat) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 社团简介 -->
          <div class="detail-section">
            <h3>社团简介</h3>
            <div class="description-box">
              <p class="short-desc">{{ currentClub.des || '暂无简介' }}</p>
              <div class="full-desc" v-if="currentClub.description">
                <h4>详细描述</h4>
                <p>{{ currentClub.description }}</p>
              </div>
            </div>
          </div>
          
          <!-- 社团图片 -->
          <div class="detail-section">
            <h3>社团图片</h3>
            <div class="image-container">
              <div class="image-item">
                <h4>社团头像</h4>
                <el-image 
                  v-if="currentClub.avatar" 
                  :src="currentClub.avatar" 
                  fit="cover"
                  style="width: 200px; height: 200px; border-radius: 8px;">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div v-else class="no-image">
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无头像</span>
                </div>
              </div>
              
              <div class="image-item">
                <h4>社团公告图</h4>
                <el-image 
                  v-if="currentClub.placard" 
                  :src="currentClub.placard" 
                  fit="cover"
                  style="width: 300px; height: 150px; border-radius: 8px;">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div v-else class="no-image">
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无公告图</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 审核意见 -->
          <div class="review-section">
            <h3>审核意见</h3>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见（选填）"
              v-model="reviewComment">
            </el-input>
          </div>
        </div>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="clubDetailVisible = false">取 消</el-button>
          <el-button type="danger" @click="handleReject(currentClub)">拒 绝</el-button>
          <el-button type="primary" @click="handleApprove(currentClub)">通 过</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import httpInstance from "@/utils/http";

  export default {
    name: 'ClubApproval',
    data() {
      return {
        // 社团列表查询参数
        clubListQuery: {
          page: 1,
          limit: 10,
          keyword: '',
          category: '',
          status: ''
        },
        // 社团类别选项
        categoryOptions: [
          { value: '学术科技', label: '学术科技' },
          { value: '文化艺术', label: '文化艺术' },
          { value: '体育运动', label: '体育运动' },
          { value: '社会实践', label: '社会实践' },
          { value: '志愿公益', label: '志愿公益' }
        ],
        // 社团列表数据
        clubList: [],
        clubTotal: 0,
        clubListLoading: true,
        
        // 社团详情对话框
        clubDetailVisible: false,
        currentClub: null,
        reviewComment: '',
        
        // 模拟社团活动数据
        clubActivities: [
          { time: '2023-10-15', content: '新生见面会', type: 'success' },
          { time: '2023-11-20', content: '技术分享讲座', type: 'primary' },
          { time: '2023-12-10', content: '年终总结大会', type: 'warning' }
        ],
        
        // 模拟社团成员数据
        clubMembers: [
          { name: '张三', role: '社长', major: '计算机科学', grade: '大三' },
          { name: '李四', role: '副社长', major: '软件工程', grade: '大二' },
          { name: '王五', role: '技术总监', major: '人工智能', grade: '大四' }
        ],
        
        // 模拟附件数据
        attachments: [
          { name: '社团章程.pdf', icon: 'el-icon-document', url: '#' },
          { name: '活动计划.docx', icon: 'el-icon-document-word', url: '#' },
          { name: '成员名单.xlsx', icon: 'el-icon-document-excel', url: '#' }
        ]
      };
    },
    created() {
      // 检查token是否存在
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/admin/login')
      }
      
      this.getClubList();
    },
    methods: {
      // 获取社团列表
      getClubList() {
        this.clubListLoading = true;
        
        // 构建请求参数
        const params = {
          page: this.clubListQuery.page,
          limit: this.clubListQuery.limit,
          keyword: this.clubListQuery.keyword || undefined,
          tags: this.clubListQuery.category || undefined,
          stat: this.mapStatusToStat(this.clubListQuery.status)
        };
        
        // 调用后端API
        httpInstance.post('/api/club/approveList', params)
          .then(response => {
            if (response.code === 200) {
              // 处理返回的数据
              this.processClubList(response.data);
            } else {
              this.$message.error(response.msg || '获取社团列表失败');
              this.clubList = [];
              this.clubTotal = 0;
            }
          })
          .catch(error => {
            console.error('获取社团列表失败:', error);
            this.$message.error('获取社团列表失败，请稍后重试');
            this.clubList = [];
            this.clubTotal = 0;
          })
          .finally(() => {
            this.clubListLoading = false;
          });
      },
      
      // 处理返回的社团列表数据
      processClubList(data) {
        if (!data) {
          this.clubList = [];
          this.clubTotal = 0;
          return;
        }
        
        // 如果返回的是分页数据
        if (data.records && Array.isArray(data.records)) {
          this.clubList = data.records.map(club => this.formatClubData(club));
          this.clubTotal = data.total || data.records.length;
        } 
        // 如果直接返回的是数组
        else if (Array.isArray(data)) {
          this.clubList = data.map(club => this.formatClubData(club));
          this.clubTotal = data.length;
        } 
        else {
          this.clubList = [];
          this.clubTotal = 0;
        }
      },
      
      // 格式化社团数据
      formatClubData(club) {
        return {
          id: club.id,
          name: club.title,
          category: club.tags,
          president: club.presidentName || '未指定',
          createTime: this.formatDate(club.createTime),
          status: this.mapStatToStatus(club.stat),
          description: club.description || '暂无描述',
          // 保存原始数据，用于详情展示和操作
          rawData: club
        };
      },
      
      // 将前端状态映射到后端stat值
      mapStatusToStat(status) {
        const statusMap = {
          'pending': 0,   // 待审核
          'approved': 1,  // 正常
          'rejected': 2,  // 否定
          'canceled': 3   // 注销
        };
        return status ? statusMap[status] : undefined;
      },
      
      // 将后端stat值映射到前端状态
      mapStatToStatus(stat) {
        const statMap = {
          0: 'pending',   // 待审核
          1: 'approved',  // 正常
          2: 'rejected',  // 否定
          3: 'canceled'   // 注销
        };
        return statMap[stat] || 'unknown';
      },
      
      // 格式化日期
      formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      },
      
      // 刷新列表
      refreshClubList() {
        this.getClubList();
      },
      
      // 处理筛选
      handleClubFilter() {
        this.clubListQuery.page = 1;
        this.getClubList();
      },
      
      // 处理每页数量变化
      handleSizeChange(val) {
        this.clubListQuery.limit = val;
        this.getClubList();
      },
      
      // 处理页码变化
      handleCurrentChange(val) {
        this.clubListQuery.page = val;
        this.getClubList();
      },
      
      // 获取状态标签类型
      getStatusType(status) {
        const statusMap = {
          pending: 'warning',
          approved: 'success',
          rejected: 'danger',
          canceled: 'info'
        };
        return statusMap[status] || 'info';
      },
      
      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          pending: '待审核',
          approved: '已通过',
          rejected: '已拒绝',
          canceled: '已注销'
        };
        return statusMap[status] || '未知';
      },
      
      // 获取标签类型
      getTagType(category) {
        category = category.trim();
        const typeMap = {
          '学术科技': 'primary',
          '文化艺术': 'success',
          '体育运动': 'warning',
          '社会实践': 'danger',
          '志愿公益': 'info'
        };
        
        // 如果找不到精确匹配，尝试部分匹配
        if (typeMap[category]) {
          return typeMap[category];
        }
        
        // 部分匹配
        if (category.includes('学术') || category.includes('科技')) return 'primary';
        if (category.includes('文化') || category.includes('艺术')) return 'success';
        if (category.includes('体育') || category.includes('运动')) return 'warning';
        if (category.includes('社会') || category.includes('实践')) return 'danger';
        if (category.includes('志愿') || category.includes('公益')) return 'info';
        
        // 默认返回
        return '';
      },
      
      // 打开社团详情对话框
      openClubDetail(club) {
        this.currentClub = club;
        this.reviewComment = '';
        this.clubDetailVisible = true;
        
        // 如果需要，可以在这里加载社团的详细信息
        this.loadClubDetail(club.id);
      },
      
      // 加载社团详细信息
      loadClubDetail(clubId) {
        // 如果需要从后端获取更详细的社团信息，可以在这里实现
        httpInstance.get(`/api/club/detail/${clubId}`)
          .then(response => {
            if (response.code === 200 && response.data) {
              // 更新当前社团的详细信息
              const detailData = response.data;
              this.currentClub = {
                ...this.currentClub,
                // 更新详细信息
                description: detailData.description,
                // 其他详细字段...
                avatar: detailData.avatar,
                placard: detailData.placard,
                stat: detailData.stat
              };
              
              // 如果API返回了活动和成员信息，也可以更新
              if (detailData.activities) {
                this.clubActivities = detailData.activities;
              }
              if (detailData.members) {
                this.clubMembers = detailData.members;
              }
            }
          })
          .catch(error => {
            console.error('获取社团详情失败:', error);
          });
      },
      
      // 关闭对话框
      handleCloseDialog() {
        this.clubDetailVisible = false;
      },
      
      // 预览文件
      previewFile(file) {
        this.$message.info(`预览文件: ${file.name}`);
        // 实际项目中可以打开文件预览
        if (file.url && file.url !== '#') {
          window.open(file.url, '_blank');
        }
      },
      
      // 审核通过
      handleApprove(club) {
        this.$confirm(`确定通过"${club.name}"的申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          // 调用审核通过API
          httpInstance.post(`/api/club/approve`, {
            clubId: club.id,
            stat: 1,  // 设置为正常状态
            remark: this.reviewComment
          })
          .then(response => {
            if (response.code === 200) {
              this.$message.success(`已通过"${club.name}"的申请`);
              this.clubDetailVisible = false;
              // 更新列表
              this.getClubList();
            } else {
              this.$message.error(response.msg || '操作失败');
            }
          })
          .catch(error => {
            console.error('审核操作失败:', error);
            this.$message.error('操作失败，请稍后重试');
          });
        }).catch(() => {
          // 取消操作
        });
      },
      
      // 拒绝申请
      handleReject(club) {
        this.$confirm(`确定拒绝"${club.name}"的申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用拒绝API
          httpInstance.post(`/api/club/approve`, {
            clubId: club.id,
            stat: 2,  // 设置为拒绝状态
            remark: this.reviewComment
          })
          .then(response => {
            if (response.code === 200) {
              this.$message.info(`已拒绝"${club.name}"的申请`);
              this.clubDetailVisible = false;
              // 更新列表
              this.getClubList();
            } else {
              this.$message.error(response.msg || '操作失败');
            }
          })
          .catch(error => {
            console.error('审核操作失败:', error);
            this.$message.error('操作失败，请稍后重试');
          });
        }).catch(() => {
          // 取消操作
        });
      },
      
      // 获取状态类型
      getStatusTypeByValue(value) {
        const statusMap = {
          0: 'warning',   // 待审核
          1: 'success',   // 正常
          2: 'danger',    // 否定
          3: 'info'       // 注销
        };
        return statusMap[value] || 'info';
      },
      
      // 获取状态文本
      getStatusTextByValue(value) {
        const statusMap = {
          0: '待审核',
          1: '正常',
          2: '已拒绝',
          3: '已注销'
        };
        return statusMap[value] || '未知';
      },
      
      // 获取活动级别颜色
      getActivityLevelColor(level) {
        const colorMap = {
          0: '#909399',
          1: '#67C23A',
          2: '#E6A23C',
          3: '#F56C6C'
        };
        return colorMap[level] || '#909399';
      },
      
      // 格式化日期时间
      formatDateTime(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
      }
    }
  }
  </script>
  
  <style scoped>
  .club-approval {

    /* padding: px; */
  }
  
  .filter-container {
    padding-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .filter-item {
    margin-right: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    padding: 15px 0;
    text-align: right;
  }
  
  /* 社团详情对话框样式 */
  .club-detail {
    margin-bottom: 20px;
  }
  
  .detail-section {
    margin-top: 30px;
  }
  
  .detail-section h3 {
    font-size: 16px;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    color: #303133;
  }
  
  .detail-section p {
    line-height: 1.6;
    color: #606266;
  }
  
  .attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-top: 15px;
  }
  
  .attachment-item {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    width: calc(50% - 8px);
  }
  
  .attachment-item i {
    font-size: 20px;
    margin-right: 10px;
    color: #909399;
  }
  
  .attachment-item span {
    flex: 1;
    color: #606266;
  }
  
  .review-section {
    margin-top: 30px;
  }
  
  .review-section h3 {
    font-size: 16px;
    margin-bottom: 15px;
    color: #303133;
  }
  
  /* 确保对话框内容可滚动 */
  .el-dialog__body {
    max-height: 60vh;
    overflow-y: auto;
  }
  
  /* 社团详情样式 */
  .description-box {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .short-desc {
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    margin-bottom: 15px;
  }
  
  .full-desc h4 {
    font-size: 15px;
    margin-bottom: 10px;
    color: #303133;
  }
  
  .full-desc p {
    font-size: 14px;
    line-height: 1.8;
    color: #606266;
    white-space: pre-line;
  }
  
  .image-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 15px;
  }
  
  .image-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .image-item h4 {
    margin-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  
  .no-image {
    width: 200px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
    border-radius: 8px;
    color: #909399;
  }
  
  .no-image i {
    font-size: 40px;
    margin-bottom: 10px;
  }
  
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #f5f7fa;
    color: #909399;
  }
  
  .image-slot i {
    font-size: 30px;
  }
  </style>